//
//  HGDataBase.m
//  个人项目(豆瓣元旦作业)
//
//  Created by dllo on 16/1/8.
//  Copyright © 2016年 guoguo. All rights reserved.
//

#import "HGDataBase.h"

@implementation HGDataBase

//创建单例对象
+ (HGDataBase *)sharedHGDataBase{
    
    static HGDataBase *hg = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hg = [[HGDataBase alloc] init];
    });
    
    return hg;
}

//打开数据库
- (void)openDB{
    
   //获取沙盒路径
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    //拼接数据库路径
    
    NSString *path = [document stringByAppendingPathComponent:@"doubanGuoGuo.sqlite"];
    
    NSLog(@"%@", path);
    
    //打开数据库
    int result = sqlite3_open(path.UTF8String, &dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"打开成功");
    }else{
        NSLog(@"打开失败");
    }
    
}

//创建表单

- (void)createTable{
    
    //sql语句
    
    NSString *sqlStr = [NSString stringWithFormat:@"create table if not exists Movie (number integer primary key autoincrement, title text  )"];
    //执行sql语句
    
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    
    if ( result == SQLITE_OK) {
        NSLog(@"创建成功");
    }else{
        NSLog(@"创建失败");
    }
    
}

//插入数据

- (void)insertData:(Movie *)model{
    
    //sql语句
    
    NSString *sqlStr = [NSString stringWithFormat:@"insert into Movie (title) values('%@')", model.title ];
    
    //执行语句
    
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"插入成功");
        
       

    }else{
        NSLog(@"插入失败");
    }
    
}
    

//删除数据
- (void)deleteData:(Movie *)model{
    
    //sql语句
    NSString *sqlStr = [NSString stringWithFormat:@"delete from Movie where title = '%@'", model.title];
    
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    
    if (result == SQLITE_OK) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }
    
    
    
    
}
    
//查询数据

- (NSMutableArray *)selectData{
    
    NSString *sqlStr = [NSString stringWithFormat:@"select * from Movie"];
    
    //创建跟随指针
    
    sqlite3_stmt *stmt = nil;
    
    //进入查询
    int result = sqlite3_prepare_v2(dbPoint, sqlStr.UTF8String, -1, &stmt, NULL);
    
    NSMutableArray *arr = [NSMutableArray array];
    
    if (result == SQLITE_OK) {
        
        
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            Movie *model = [Movie movie];
            const unsigned char *title = sqlite3_column_text(stmt, 1);
            
            model.title = [NSString stringWithUTF8String:(const char *)title];
            [arr addObject:model];
            
            NSLog(@"%@", arr);
        }
        
        
    }
    
    
    return arr;
    
}






@end
